#region (c) 2009 Rinat Abdullin

// Copyright (c) Rinat Abdullin
// All Rights Reserved
// Site: http://abdullin.com

#endregion

using System;
using NCouch.Json;
using NCouch.Model;
using NCouch.Rest;

namespace NCouch
{
	public static class CouchFactory
	{
		public static CouchServer ConnectToServer(string url)
		{
			var restClient = BuildDebuggingCouchRestClient(url);
			return new CouchServer(restClient);
		}


		public static CouchDatabase ConnectToDatabase(string url)
		{
			var restClient = BuildDebuggingCouchRestClient(url);
			return new CouchDatabase(restClient);
		}

		static CouchRestClient BuildDebuggingCouchRestClient(string url) {
			var serializer = AssembleSerializer();
			var client = new RestClient();

			
			var debugger = new RestClientDebuggingDecorator(client);

			debugger.OnRequest += RestClientDebugger.Print;
			debugger.OnResponse += RestClientDebugger.Print;
			
			return new CouchRestClient(serializer, debugger, new Uri(url));
		}

		static JayrockSerializer AssembleSerializer()
		{
			var serializer = new JayrockSerializer()
				.WithCSharpModel<ServerInfo>()
				.WithCSharpModel<RevisionInfo>()
				.WithCSharpModel<DatabaseInfo>()
				.WithCSharpModel<ErrorInfo>()
				.WithCSharpModel<MapView>();

			

			Overloads(serializer);
			return serializer;
		}

		static Action<JayrockSerializer> Overloads = js => { };

		public static void Build(Action<JayrockSerializer> overload)
		{
			Overloads += overload;
		}
	}
}